package websocket

import okhttp3.*
import java.util.*
import kotlin.concurrent.timer


fun main(args: Array<String>) {

    val client = OkHttpClient.Builder().build()
    client.newWebSocket(Request.Builder().url("ws://localhost:39912/").build(), object : WebSocketListener() {
        override fun onOpen(webSocket: WebSocket, response: Response) {
            System.out.println("client onOpen")
            System.out.println("client request header:" + response.request().headers())
            System.out.println("client response header:" + response.headers())
            System.out.println("client response:" + response)

            timer(period = 5 * 1000L) {
                //除了文本内容外，还可以将如图像，声音，视频等内容转为ByteString发送
                webSocket.send("客户端发送的信心：${Date()}")
            }
        }

        override fun onFailure(webSocket: WebSocket, t: Throwable?, response: Response?) {
            //出现异常会进入此回调
            System.out.println("client onFailure")
            System.out.println("throwable:" + t)
            System.out.println("response:" + response)
        }

        override fun onClosing(webSocket: WebSocket, code: Int, reason: String?) {
            System.out.println("client onClosing")
            System.out.println("code:" + code + " reason:" + reason)
        }

        override fun onMessage(webSocket: WebSocket, text: String?) {
            System.out.println("client onMessage")
            System.out.println("message:" + text)
        }


        override fun onClosed(webSocket: WebSocket, code: Int, reason: String?) {
            System.out.println("client onClosed")
            System.out.println("code:" + code + " reason:" + reason)
        }
    })

}